<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isAdd ? '新增模板头' : '编辑模板头'"
    width="500px"
    @close="resetForm"
  >
    <el-form ref="serviceForm" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="名称" prop="title">
        <el-input v-model="form.title" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          placeholder="请输入描述"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" :loading @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { message } from "@/utils/message";
import {
  createAdminTemplateHead,
  updateAdminTemplateHead
} from "@/api/adminTemplateHeadApi";

const emits = defineEmits(["refresh"]);
const dialogVisible = ref(false);
const loading = ref(false);
const form = ref({
  title: "",
  description: ""
});
const templateId = ref("");
// 基础校验规则
const rules = {
  standardCode: [{ required: true, message: "请输入名称", trigger: "blur" }]
};
const isAdd = computed(() => !templateId.value);
const serviceForm = ref(null);
// 重置表单
const resetForm = () => {
  templateId.value = "";
  form.value = {
    title: "",
    description: ""
  };
  serviceForm.value?.clearValidate();
  serviceForm.value?.resetFields();
};

const handleConfirm = () => {
  serviceForm.value.validate(async valid => {
    if (valid) {
      try {
        loading.value = true;
        if (isAdd.value) {
          const { message: text } = await createAdminTemplateHead(form.value);
          message(text || "创建成功", { type: "success" });
        } else {
          const { message: text } = await updateAdminTemplateHead(
            templateId.value,
            form.value
          );
          message(text || "更新成功", { type: "success" });
        }
        emits("refresh");
        dialogVisible.value = false;
      } catch (error) {
        console.log(error);
      } finally {
        loading.value = false;
      }
    }
  });
};
const open = (row: { id: string; title: string; description: string }) => {
  if (row?.id) {
    templateId.value = row.id;
    form.value = {
      title: row.title,
      description: row.description
    };
  }
  dialogVisible.value = true;
};
defineExpose({
  open
});
</script>
